<?php
namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Builder;
use Ramsey\Uuid\Uuid;
use App\Models\User;
use App\Models\Forum;
use App\Models\Comment;

class Topic extends Model
{
    use SoftDeletes;

    const TYPE_GENERAL = 1;

    const TYPE_REPORT = 2;

    public static $types = [
        self::TYPE_GENERAL => '普通',
        self::TYPE_REPORT => '报告',
    ];

    //新建帖子默认敏感度，极高，100
    //@todo
    const DEFAULT_SENSITIVITY = 1;

    //详情页每页评论数量
    const DETAIL_COMMENT_PAGE_SIZE = 10;
    //详情页每页评论的评论的数量
    const DETAIL_COMMENT_COMMENT_PAGE_SIZE = 5;

    const HAS_HIDE = 0b1; //是否有隐藏部分
    const HAS_ATTACHMENT = 0b10; //是否有图片
    const IS_SPOTLIGHT = 0b100; //是否精华
    const IS_STICKY = 0b1000; //是否置顶


    protected $fillable = [
        'key', 'type', 'title', 'fid', 'uid',
        'action_time', 'action_location', 'action_province', 'action_city', 'action_district', 'longitude', 'latitude',
        'view_count', 'comment_count', 'last_comment_time', 'last_comment_id',
    ];

    protected $appends = ['is_report'];


    public static function booted()
    {
        static::creating(function (Model $model) {
            $model->key = Uuid::uuid4();
            $model->sensitivity = self::DEFAULT_SENSITIVITY;
        });

        static::addGlobalScope('sensitivity', function (Builder $builder) {
            if (is_module_api()) {
                $builder->where(function (Builder $query) {
                    $user = auth_user();
                    $sensitivityAbility = $user ? $user->sensitivity_ability : User::DEFAULT_SENSITIVITY_ABILITY;
                    $query->where('sensitivity', '<=', $sensitivityAbility)->orWhere('uid', $user->id);
                });
            }
        });

    }

    public function hasHide()
    {
        return ($this->mask_code & self::HAS_HIDE) == self::HAS_HIDE;
    }

    public function hasAttachment()
    {
        return ($this->mask_code & self::HAS_ATTACHMENT) == self::HAS_ATTACHMENT;
    }

    public function isSpotlight()
    {
        return ($this->mask_code & self::IS_SPOTLIGHT) == self::IS_SPOTLIGHT;
    }
    public function isSticky()
    {
        return ($this->mask_code & self::IS_STICKY) == self::IS_STICKY;
    }

    public function getTypeNameAttribute()
    {
        return self::$types[$this->type] ?? '';
    }

    public function getTitleExcerptAttribute($limit = 100)
    {
        if ($this->title) {
            if ($limit) {
                return Str::limit($this->title, $limit);
            }
            return $this->title;
        }
        $comment = $this->mainFloor;
        return $comment->detail_excerpt;
    }

    public function getIsReportAttribute()
    {
        return intval($this->type == self::TYPE_REPORT);
    }

    public function scopeTypeGeneral($query)
    {
        return $query->where('type', self::TYPE_GENERAL);
    }

    public function scopeTypeReport($query)
    {
        return $query->where('type', self::TYPE_REPORT);
    }
    
    /**
     * 话题作者
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'uid', 'id');
    }
    
    /**
     * 主题所属版块
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function forum()
    {
        return $this->belongsTo(Forum::class, 'fid', 'id')->withDefault([
            'id' => 0,
            'name' => '(不存在)',
        ]);
    }
    
    /**
     * 话题最后回复
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function lastComment()
    {
        return $this->hasOne(Comment::class, 'id', 'last_comment_id');
    }
    
    /**
     * 话题主楼回复
     * 
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function mainFloor()
    {
        return $this->hasOne(Comment::class, 'tid', 'id')->where("floor_num", 1)->withTrashed();
    }

    /**
     * 话题全部回复
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany(Comment::class, "tid", "id")->where('is_main_floor', 0);
    }

    /**
     * 话题直接回复（非楼中楼）
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function directComments()
    {
        return $this->comments()->where('pid', 0);
    }

    /**
     * 话题标签
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'topic_tags', 'tid', 'tag_id')
            ->withTimestamps();
    }

    public function operationLogs()
    {
        return $this->hasMany(TopicOperationLog::class, 'tid', 'id');
    }

    public function lastOperationLog()
    {
        return $this->hasOne(TopicOperationLog::class, 'tid', 'id')->where('is_latest', 1);
    }

    public function stickyInfo()
    {
        return $this->hasOne(StickyTopic::class, 'tid','id');
    }


}
